package com.gcd.gym.api;


import com.gcd.gym.model.Account;
import com.gcd.gym.model.Admin;
import com.gcd.gym.service.LoginService;
import com.gcd.gym.utils.JsonResult;
import com.gcd.gym.utils.JwtUtil;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/api/v1/login")
@RestController
public class LoginApi {

    private RedisTemplate<Object, Object> redisTemplate;
    private LoginService loginService;
    private final static StrongPasswordEncryptor PE=new StrongPasswordEncryptor();
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    public void setAccountService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/captcha")
    public void captcha(String id,HttpServletRequest request, HttpServletResponse response) throws IOException {


        SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);
        response.setContentType("image/gif");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        redisTemplate.opsForValue().set("captcha"+id, captcha.text().toLowerCase(), Duration.ofMinutes(1));
        captcha.out(response.getOutputStream());
    }


    @PostMapping
    public ResponseEntity<JsonResult<?>> login(@RequestBody Account account) {
        if (account.getCaptchaId() == null || account.getCaptchaId().isEmpty()) {
            return ResponseEntity.ok(JsonResult.fail("验证码ID不能为空"));
        }
        String correct=(String) redisTemplate.opsForValue().get("captcha" + account.getCaptchaId());
        if(!account.getCaptcha().equals( correct)) {
            return ResponseEntity.ok(JsonResult.fail("验证码错误"));
        }
        Admin admin = loginService.findByPhone(account.getUsername());
        if(admin == null) {
            return ResponseEntity.ok(JsonResult.fail("用户不存在"));
        }

        boolean pass=PE.checkPassword(account.getPassword(),admin.getPassword());
        if (!pass) {
            return ResponseEntity.ok(JsonResult.fail("密码错误"));
        }

        String jwt= JwtUtil.createJwt(UUID.randomUUID().toString(),admin.getPhone(), Map.of("username",admin.getPhone(),"userId",admin.getId()),
                LocalDateTime.now().plusMinutes(30),jwtSecret);

        System.out.println(jwt);

        return ResponseEntity.ok(JsonResult.success(jwt));
    }
}
